package com.isoft.c2team3service2.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.isoft.c2team3service2.dto.HotPostDTO;
import com.isoft.c2team3service2.dto.PostDTO;
import com.isoft.c2team3service2.entity.HotPost;
import com.isoft.c2team3service2.entity.Post;
import com.isoft.c2team3service2.mapper.HotPostMapper;
import com.isoft.c2team3service2.mapper.PostMapper;
import com.isoft.c2team3service2.service.HotPostService;
import com.isoft.c2team3service2.service.PostService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

import static com.isoft.c2team3service2.util.RedisConstants.HOT_POST;

@Service
@RequiredArgsConstructor
public class HotPostServiceImpl implements HotPostService {

    private final HotPostMapper hotPostMapper;
    // 注入 PostService，用于校验 postId 合法性
    private final PostService postService;
    private final ObjectMapper objectMapper;
    private final PostMapper postMapper;
    private final StringRedisTemplate stringRedisTemplate;

    // 原有：查询热门帖子列表（保留）
   @Override
    public List<PostDTO> getHotPostList() {
    QueryWrapper<Post> rapper = new QueryWrapper<>();

    rapper.eq("status", 4);

    List<Post> posts = postMapper.selectList(rapper);

//     使用stream将Post映射到PostDTO
    List<PostDTO> postDTOS = posts.stream()
            .map(this::convertPostToDTO)
            .collect(Collectors.toList());

       try {
           String jsonValue = objectMapper.writeValueAsString(postDTOS);
           stringRedisTemplate.opsForValue().set(HOT_POST, jsonValue);
       } catch (JsonProcessingException e) {
           e.printStackTrace();
       }

    return postDTOS;
    }

    private PostDTO convertPostToDTO(Post post) {
        PostDTO dto = new PostDTO();
        dto.setId(post.getId());
        dto.setTitle(post.getTitle());
        dto.setNickName(post.getNickName());
        dto.setContent(post.getContent());
        dto.setViewCount(post.getViewCount());
        dto.setLikeCount(post.getLikeCount());
        dto.setPrice(post.getPrice());
        dto.setCommentCount(post.getCommentCount());
        dto.setCreateTime(post.getCreateTime());
        dto.setUpdateTime(post.getUpdateTime());
        dto.setStatus(post.getStatus());
        dto.setArtist(post.getArtist());
        dto.setIsPaid(post.getIsPaid());
        dto.setUserId(post.getUserId());
        dto.setIsArtistCommand(post.getIsArtistCommand());
        dto.setPhotoUrl(post.getPhotoUrl());
        dto.setArtistName(post.getArtistName());
        return dto;
    }


    // 新增1：添加热门帖子
    @Override
    @Transactional
    public boolean addHotPost(Integer hotPost) {
        Post post = postService.findById(hotPost);
        post.setStatus(4);

        // 校验该 postId 是否已关联热门帖子（防重复）
        if (existsByPostId(hotPost)) {
            throw new IllegalArgumentException("该帖子已添加为热门（postId: " + hotPost + "）");
        }

        return postMapper.updateById(post)> 0;
    }

    // 新增2：删除热门帖子
    @Override
    @Transactional
    public boolean deleteHotPost(Integer hotPostId) {
        // 1. 校验热门帖子是否存在
        Post post = postMapper.selectById(hotPostId);
        if (post != null && !existsByPostId(hotPostId)) {
            throw new IllegalArgumentException("热门帖子不存在（id: " + hotPostId + "）");
        }
        post.setStatus(1);

        // 2. 删除热门帖子（仅删除 hot_post 记录，不影响 post 表）
        return postMapper.updateById(post) > 0;
    }

    // 新增3：修改热门帖子
    @Override
    @Transactional
    public boolean updateHotPost(HotPost hotPost) {
        Long hotPostId = hotPost.getId();
        // 1. 校验热门帖子是否存在
        HotPost existingHotPost = hotPostMapper.selectById(hotPostId);
        if (existingHotPost == null) {
            throw new IllegalArgumentException("热门帖子不存在（id: " + hotPostId + "）");
        }

        // 2. 禁止修改 postId（关联关系不可变更）
        if (hotPost.getPostId() != null && !hotPost.getPostId().equals(existingHotPost.getPostId())) {
            throw new IllegalArgumentException("不允许修改关联的帖子（postId 不可变更）");
        }

        // 3. 仅更新允许修改的字段（标题、来源、图片、排序等）
        HotPost updateEntity = new HotPost();
        updateEntity.setId(hotPostId);
        updateEntity.setTitle(hotPost.getTitle() != null ? hotPost.getTitle() : existingHotPost.getTitle());
        updateEntity.setSource(hotPost.getSource() != null ? hotPost.getSource() : existingHotPost.getSource());
        updateEntity.setImgSrc(hotPost.getImgSrc() != null ? hotPost.getImgSrc() : existingHotPost.getImgSrc());
        updateEntity.setTime(hotPost.getTime() != null ? hotPost.getTime() : existingHotPost.getTime());
        updateEntity.setIsAd(hotPost.getIsAd() != null ? hotPost.getIsAd() : existingHotPost.getIsAd());
        updateEntity.setIsHot(hotPost.getIsHot() != null ? hotPost.getIsHot() : existingHotPost.getIsHot());
        updateEntity.setLikeCount(hotPost.getLikeCount() != null ? hotPost.getLikeCount() : existingHotPost.getLikeCount());
        updateEntity.setSortOrder(hotPost.getSortOrder() != null ? hotPost.getSortOrder() : existingHotPost.getSortOrder());

        // 4. 执行更新
        return hotPostMapper.updateById(updateEntity) > 0;
    }

    // 新增4：查询单个热门帖子
    @Override
    public HotPostDTO getHotPostById(Long hotPostId) {
        HotPost hotPost = hotPostMapper.selectById(hotPostId);
        return hotPost != null ? convertToDTO(hotPost) : null;
    }

    // 新增5：校验 postId 是否已关联热门帖子
    @Override
    public boolean existsByPostId(Integer postId) {
        QueryWrapper<Post> wrapper = new QueryWrapper<>();
        wrapper.eq("id", postId)
                .eq("status", 4);
        return postMapper.selectCount(wrapper) > 0;
    }

    // 工具方法：HotPost 转 HotPostDTO
    private HotPostDTO convertToDTO(HotPost hotPost) {
        HotPostDTO dto = new HotPostDTO();
        dto.setId(hotPost.getId());
        dto.setTitle(hotPost.getTitle());
        dto.setSource(hotPost.getSource());
        dto.setImgSrc(hotPost.getImgSrc());
        dto.setTime(hotPost.getTime());
        dto.setIsAd(hotPost.getIsAd());
        dto.setIsHot(hotPost.getIsHot());
        dto.setLikeCount(hotPost.getLikeCount());
        return dto;
    }

}